/*******************************************************************************
 * Copyright 2009-2015 Amazon Services. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 *
 * You may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 
 * specific language governing permissions and limitations under the License.
 *******************************************************************************
 * Marketplace Web Service Orders
 * API Version: 2013-09-01
 * Library Version: 2015-04-30
 * Generated: Thu May 28 20:14:49 GMT 2015
 */
package com.amazonservices.mws.orders._2013_09_01.samples;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.datatype.XMLGregorianCalendar;

import com.alibaba.fastjson.JSON;
import com.amazon.list.GetOrdersList;
import com.amazon.list.Order;
import com.amazonservices.mws.client.MwsUtl;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrders;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersClient;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersException;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrdersRequest;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrdersResponse;
import com.amazonservices.mws.orders._2013_09_01.model.ResponseHeaderMetadata;
import com.idp.ebay.domain.AmazonInfo;
import com.idp.ebay.utils.ExcelFileUtil;

import cn.creditharmony.loan.util.Xml2JsonUtil;

/** Sample call for ListOrders. */
public class ListOrdersSample {

	/**
	 * Call the service, log response and exceptions.
	 *
	 * @param client
	 * @param request
	 *
	 * @return The response.
	 */
	public static ListOrdersResponse invokeListOrders(MarketplaceWebServiceOrders client, ListOrdersRequest request) {
		try {

			// Call the service.
			ListOrdersResponse response = client.listOrders(request);

			ResponseHeaderMetadata rhmd = response.getResponseHeaderMetadata();
			// We recommend logging every the request id and timestamp of every
			// call.
			System.out.println("Response:");
			System.out.println("RequestId: " + rhmd.getRequestId());
			System.out.println("Timestamp: " + rhmd.getTimestamp());
			String responseXml2 = response.toXML();
			System.out.println(responseXml2);

			String jsonstr = Xml2JsonUtil.xml2JSON(responseXml2);

			ExcelFileUtil excel = new ExcelFileUtil();

			System.out.println(jsonstr);

			GetOrdersList getO = JSON.parseObject(jsonstr, GetOrdersList.class);

			List<Order> orderlist = getO.getListOrdersResponse().getListOrdersResult().get(0).getOrders().get(0)
					.getOrder();

			List<AmazonInfo> ebst = new ArrayList<AmazonInfo>();

			AmazonInfo amazonInfo;
			String EarliestDeliveryDate = "";
			String EarliestShipDate = "";
			String ShippedByAmazonTFM = "";
			String ShipServiceLevel = "";
			String LatestDeliveryDate = "";
			String PurchaseDat = "";
			String AmazonOrderId = "";
			String BuyerEmail = "";
			String BuyerName = "";
			String FulfillmentChannel = "";
			String ShippingAddress = "";
			String PaymentMethod = "";
			String OrderTotal = "";
			String LastUpdateDate = "";

			for (Order o : orderlist) {

				if (o.getAmazonOrderId() == null) {

					System.out.println("订单获取完成");

				} else {

					if (o.getEarliestDeliveryDate() == null) {
						EarliestDeliveryDate = "";
					} else {
						EarliestDeliveryDate = o.getEarliestDeliveryDate().toString();
					}

					if (o.getEarliestShipDate() == null) {
						EarliestShipDate = "";
					} else {
						EarliestShipDate = o.getEarliestShipDate().toString();
					}

					if (o.getShippedByAmazonTFM() == null) {
						ShippedByAmazonTFM = "";
					} else {
						ShippedByAmazonTFM = o.getShippedByAmazonTFM().get(0);
					}

					if (o.getShipServiceLevel() == null) {
						ShipServiceLevel = "";
					} else {
						ShipServiceLevel = o.getShipServiceLevel().get(0);
					}

					if (o.getLatestDeliveryDate() == null) {
						LatestDeliveryDate = "";
					} else {
						LatestDeliveryDate = o.getLatestDeliveryDate().toString();
					}

					if (o.getPurchaseDate() == null) {
						PurchaseDat = "";
					} else {
						PurchaseDat = o.getPurchaseDate().toString();
					}

					if (o.getAmazonOrderId() == null) {
						AmazonOrderId = "订单获取完成";
					} else {
						AmazonOrderId = o.getAmazonOrderId().get(0);
					}

					if (o.getBuyerEmail() == null) {
						BuyerEmail = "";
					} else {
						BuyerEmail = o.getBuyerEmail().get(0);
					}

					if (o.getBuyerName() == null) {
						BuyerName = "";
					} else {
						BuyerName = o.getBuyerName().get(0);
					}

					if (o.getFulfillmentChannel() == null) {
						FulfillmentChannel = "";
					} else {
						FulfillmentChannel = o.getFulfillmentChannel().get(0);
					}

					if (o.getShippingAddress() == null) {
						ShippingAddress = "";
					} else {
						ShippingAddress = o.getShippingAddress().get(0).toString();
					}

					if (o.getPaymentMethod() == null) {
						PaymentMethod = "";
					} else {
						PaymentMethod = o.getPaymentMethod().get(0);
					}

					if (o.getOrderTotal() == null) {
						OrderTotal = "";
					} else {
						OrderTotal = o.getOrderTotal().get(0).toString();
					}

					if (o.getLastUpdateDate() == null) {
						LastUpdateDate = "";
					} else {
						LastUpdateDate = o.getLastUpdateDate().toString();
					}
					amazonInfo = new AmazonInfo(AmazonOrderId, BuyerEmail, EarliestDeliveryDate, EarliestShipDate,
							o.getSalesChannel().get(0), o.getOrderStatus().get(0), o.getNumberOfItemsShipped().get(0),
							o.getOrderType().get(0), o.getIsPremiumOrder().get(0), o.getIsPrime().get(0), BuyerName,
							FulfillmentChannel, o.getNumberOfItemsUnshipped().get(0), o.getLatestShipDate().toString(),
							ShippedByAmazonTFM, ShipServiceLevel, o.getMarketplaceId().get(0), LatestDeliveryDate,
							PurchaseDat, ShippingAddress, PaymentMethod, o.getIsBusinessOrder().toString(), OrderTotal,
							LastUpdateDate, o.getShipmentServiceLevelCategory().get(0));
					ebst.add(amazonInfo);

				}

			}
			System.out.println(ebst.size());
			File file = excel.write("亚马逊订单信息", ebst, AmazonInfo.class, null);
			System.out.println("文件存放路径为：" + file.getPath());

			return response;
		} catch (MarketplaceWebServiceOrdersException ex) {

			System.out.println("Service Exception:");
			ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
			if (rhmd != null) {
				System.out.println("RequestId: " + rhmd.getRequestId());
				System.out.println("Timestamp: " + rhmd.getTimestamp());
			}
			System.out.println("Message: " + ex.getMessage());
			System.out.println("StatusCode: " + ex.getStatusCode());
			System.out.println("ErrorCode: " + ex.getErrorCode());
			System.out.println("ErrorType: " + ex.getErrorType());
			throw ex;
		}
	}

	/**
	 * Command line entry point.
	 */
	public static void main(String[] args) {

		// Get a client connection.
		// Make sure you've set the variables in
		// MarketplaceWebServiceOrdersSampleConfig.
		MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();

		// Create a request.
		ListOrdersRequest request = new ListOrdersRequest();
		String sellerId = "A31FK1YOBVUT0K";
		request.setSellerId(sellerId);
		String mwsAuthToken = "example";
		request.setMWSAuthToken(mwsAuthToken);
		XMLGregorianCalendar createdAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
		createdAfter.setYear(2017);
		createdAfter.setMonth(3);
		createdAfter.setDay(3);
		request.setCreatedAfter(createdAfter);
		XMLGregorianCalendar createdBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
		createdBefore.setYear(2017);
		createdBefore.setMonth(6);
		createdBefore.setDay(1);
		request.setCreatedBefore(createdBefore);
		XMLGregorianCalendar lastUpdatedAfter = MwsUtl.getDTF().newXMLGregorianCalendar();
		request.setLastUpdatedAfter(lastUpdatedAfter);
		XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
		request.setLastUpdatedBefore(lastUpdatedBefore);
		List<String> orderStatus = new ArrayList<String>();
		request.setOrderStatus(orderStatus);
		List<String> marketplaceId = new ArrayList<String>();
		marketplaceId.add("A2EUQ1WTGCTBG2");
		marketplaceId.add("ATVPDKIKX0DER");
		marketplaceId.add("A1AM78C64UM0Y8");
		request.setMarketplaceId(marketplaceId);
		List<String> fulfillmentChannel = new ArrayList<String>();
		request.setFulfillmentChannel(fulfillmentChannel);
		List<String> paymentMethod = new ArrayList<String>();
		request.setPaymentMethod(paymentMethod);
		String buyerEmail = "";
		request.setBuyerEmail(buyerEmail);
		String sellerOrderId = "";
		request.setSellerOrderId(sellerOrderId);
		Integer maxResultsPerPage = 30;
		request.setMaxResultsPerPage(maxResultsPerPage);
		List<String> tfmShipmentStatus = new ArrayList<String>();
		request.setTFMShipmentStatus(tfmShipmentStatus);

		// Make the call.
		ListOrdersSample.invokeListOrders(client, request);

	}

}
